package com.holyn.guofang.view.my;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.holyn.guofang.R;
import com.holyn.guofang.model.webhttp.HttpConfigure;
import com.holyn.guofang.model.webhttp.wo.OrderItemWo;
import com.holyn.guofang.presenter.BaseView;
import com.holyn.guofang.presenter.my.MyContract;
import com.holyn.guofang.presenter.my.MyPresenter;
import com.holyn.guofang.view.BaseActivity;
import com.holyn.guofang.viewcommon.itemdecoration.LinearLayoutItemDecoration;
import com.vondear.rxtools.RxTimeUtils;
import com.vondear.rxtools.view.dialog.RxDialogWheelYearMonthDay;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Holyn on 2017/8/22.
 */

public class MyOrderActivity extends BaseActivity implements BaseView, MyContract.OrderListView{
    private static final int REQUEST_ACTION_POST_ORDER_LIST= 0x0001;

    private static final int REQUEST_CODE_GET_ORDER_DELETE_STATUS= 0x0001;

    @BindView(R.id.tv_begin_date)
    TextView tvBeginDate;
    @BindView(R.id.ll_begin_date)
    LinearLayout llBeginDate;
    @BindView(R.id.tv_end_date)
    TextView tvEndDate;
    @BindView(R.id.ll_end_date)
    LinearLayout llEndDate;
    @BindView(R.id.btn_search)
    Button btnSearch;
    @BindView(R.id.tv_un_pay)
    TextView tvUnPay;
    @BindView(R.id.tv_has_pay)
    TextView tvHasPay;
    @BindView(R.id.rv_list)
    RecyclerView rvList;

    MyContract.Presenter presenter;

    private RxDialogWheelYearMonthDay mRxDialogWheelYearMonthDay;
    private int curDataSelectType = 1;//1代表选择开始时间，2代表选择结束时间

    String from;
    String to;
    Integer payStatus = 0;//支付状态(0:未支付，1:已支付，其余不判断该 条件)
    Integer orderType = -8;//订单类型(-1:国方卡订单，1:含主卡订单，2:仅 有附属卡订单，3:商标事宜在线委托需订单，4:商 标注册申请，其余不判断该条件)
    Integer pageSize = -1;
    Integer page = -1;

    MyRecyclerAdapter adapter;
    List<OrderItemWo.DataBean> orderList = new ArrayList<>();

    private int curClickPosition = 0;

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_my_order;
    }

    @Override
    protected void onMyCreate() {
        ButterKnife.bind(this);
        showToolbar("订单列表");

        presenter = new MyPresenter(this);
        presenter.addOrderListView(this);

        to = RxTimeUtils.getCurrentDateTime("yyyy-MM-dd");
        from = get3MonthAgo(to);
        tvBeginDate.setText(from);
        tvEndDate.setText(to);

        adapter = new MyRecyclerAdapter(orderList);
        rvList.addItemDecoration(new LinearLayoutItemDecoration(MyOrderActivity.this));
        rvList.setLayoutManager(new LinearLayoutManager(MyOrderActivity.this));
        rvList.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                curClickPosition = i;
                OrderItemWo.DataBean order = orderList.get(i);
                MyOrderDetailActivity.startForResult(MyOrderActivity.this, "MyOrderActivity", order.getId(), REQUEST_CODE_GET_ORDER_DELETE_STATUS);
            }
        });

        initWheelYearMonthDayDialog();

        presenter.postOrderList(REQUEST_ACTION_POST_ORDER_LIST, from, to, payStatus, orderType, pageSize, page);

    }

    @OnClick({R.id.ll_begin_date, R.id.ll_end_date, R.id.btn_search, R.id.tv_un_pay, R.id.tv_has_pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_begin_date:
                curDataSelectType = 1;
                mRxDialogWheelYearMonthDay.show();
                break;
            case R.id.ll_end_date:
                curDataSelectType = 2;
                mRxDialogWheelYearMonthDay.show();
                break;
            case R.id.btn_search:
                if (isDateFromLessDateTo()){
                    presenter.postOrderList(REQUEST_ACTION_POST_ORDER_LIST, from, to, payStatus, orderType, pageSize, page);
                } else {
                    toastMsg("开始时间不能大于结束时间");
                }
                break;
            case R.id.tv_un_pay:
                tvUnPay.setTextColor(ContextCompat.getColor(MyOrderActivity.this, R.color.colorPrimary));
                tvHasPay.setTextColor(ContextCompat.getColor(MyOrderActivity.this, R.color.black));
                payStatus = 0;
                presenter.postOrderList(REQUEST_ACTION_POST_ORDER_LIST, from, to, payStatus, orderType, pageSize, page);
                break;
            case R.id.tv_has_pay:
                tvUnPay.setTextColor(ContextCompat.getColor(MyOrderActivity.this, R.color.black));
                tvHasPay.setTextColor(ContextCompat.getColor(MyOrderActivity.this, R.color.colorPrimary));
                payStatus = 1;
                presenter.postOrderList(REQUEST_ACTION_POST_ORDER_LIST, from, to, payStatus, orderType, pageSize, page);
                break;
        }
    }

    private boolean isDateFromLessDateTo(){
        long fromL = RxTimeUtils.string2Milliseconds(from);
        long toL = RxTimeUtils.string2Milliseconds(to);
        if (fromL <= toL){
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void requestStart(Integer requestAction) {
        showLoadingDialog();
    }

    @Override
    public void requestError(Integer requestAction, Throwable e) {
        toastMsg("出现异常");
        closeLoadingDialog();
        orderList.clear();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void requestComplete(Integer requestAction) {
        closeLoadingDialog();
    }

    @Override
    public void responseSuccess(int requestAction, OrderItemWo orderItemWo) {
        orderList.clear();
        if (orderItemWo.getStatus() == HttpConfigure.STATUS_SUCCESS){
            List<OrderItemWo.DataBean> data = orderItemWo.getData();
            if (data != null){
                orderList.addAll(data);
            }
        } else {
            toastMsg("获取数据失败");
        }
        adapter.notifyDataSetChanged();
    }

    public String get3MonthAgo(String time){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        long month3AgoMilliseconds = RxTimeUtils.string2Milliseconds(time, format) - 92L*86400000L;
        return RxTimeUtils.milliseconds2String(month3AgoMilliseconds, format);
    }

    private void initWheelYearMonthDayDialog() {
        // ------------------------------------------------------------------选择日期开始
        mRxDialogWheelYearMonthDay = new RxDialogWheelYearMonthDay(this, 2000, 2100);
        mRxDialogWheelYearMonthDay.getCheckBox_day().setVisibility(View.GONE);
        mRxDialogWheelYearMonthDay.getYear().setCurrentItem(17);
        mRxDialogWheelYearMonthDay.getTv_sure().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        int year = mRxDialogWheelYearMonthDay.getSelectorYear();
                        String month = mRxDialogWheelYearMonthDay.getSelectorMonth();
                        String day = mRxDialogWheelYearMonthDay.getSelectorDay();
                        String date = year + "-" + month + "-" +day;
                        if (curDataSelectType == 1){
                            from = date;
                            tvBeginDate.setText(date);
                        } else if (curDataSelectType == 2){
                            to = date;
                            tvEndDate.setText(date);
                        }
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        mRxDialogWheelYearMonthDay.getTv_cancle().setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        mRxDialogWheelYearMonthDay.cancel();
                    }
                });
        // ------------------------------------------------------------------选择日期结束
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK){
            if (requestCode == REQUEST_CODE_GET_ORDER_DELETE_STATUS){
                boolean isDelete = data.getBooleanExtra(MyOrderDetailActivity.INTENT_KEY_IS_NEED_REFLASH, false);
                if (isDelete){
//                    orderList.remove(curClickPosition);
                    presenter.postOrderList(REQUEST_ACTION_POST_ORDER_LIST, from, to, payStatus, orderType, pageSize, page);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    private class MyRecyclerAdapter extends BaseQuickAdapter<OrderItemWo.DataBean, BaseViewHolder>{

        public MyRecyclerAdapter(@Nullable List<OrderItemWo.DataBean> data) {
            super(R.layout.item_my_order, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, OrderItemWo.DataBean dataBean) {
            baseViewHolder.setText(R.id.tv_order_code, dataBean.getOrderCode());
            baseViewHolder.setText(R.id.tv_price, "¥"+dataBean.getSumPrice()+"元");
            baseViewHolder.setText(R.id.tv_order_time, dataBean.getOrderTime());

            TextView tvPayStatus = baseViewHolder.getView(R.id.tv_pay_status);
            if (dataBean.isPayStatus()){
                tvPayStatus.setTextColor(ContextCompat.getColor(MyOrderActivity.this, R.color.deep_gray_2));
                tvPayStatus.setText("已付款");
            } else {
                tvPayStatus.setTextColor(ContextCompat.getColor(MyOrderActivity.this, R.color.red));
                tvPayStatus.setText("未付款");
            }
        }
    }
}
